export function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

export function verifyEmail(email) {
    if (!email) {
        alert("请输入邮箱!");
        return false;
    }
    if (!email.match(/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/)) {
        alert("邮箱格式不正确!");
        return false;
    }
    return true;
}

export function bindCaptchaBtn() {
    $("#captcha-btn").click(function (event) {
        event.preventDefault(); // 阻止默认行为
        let email = $("#email").val();
        if (!verifyEmail(email)) {
            return;
        }
        let $this = $(this);
        $this.attr("disabled", true);
        $.ajax({
            url: "/auth/capthca",
            method: 'GET',
            data: {email: email},
            success: function (data) {
                if (data.code === 200) {
                    alert('发送成功');
                } else {
                    alert(`Error:${data.message}!`);
                }
            },
            error: function (data) {
                alert(`Error:${data.message}!`);
            }
        })
        let countdowm = 30;
        let timer = setInterval(function () {
                countdowm--;
                if (countdowm > 0) {
                    $this.text(countdowm + "秒后重新发送");
                } else {
                    clearInterval(timer)
                    $this.text("发送验证码");
                    $this.attr("disabled", false);
                }

            }, 1000)
        ; // 60秒后重新启用按钮

    })

}